<template>
	<div class="vue_app">
		<my-header :title="'确认订单'"  :hasBacks="true" :goBack="goBack" :canteen ="true"></my-header>
		<div class="content" id="scanNodeBug">
			<!-- <div class="aui-content aui-margin-b-15">
				<ul class="aui-list aui-list-in">
					<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">宁家鲜生</div>
						</div>
					</li>
				</ul>
			</div> -->
            <!-- 地址距离信息 -->
            <!-- <div style="height:2rem; background-color: rgba(255, 243, 238, 1);">
                <p style="height:100%;line-height:2rem;color:#EF5423;">
                    用餐门店距离您1600.8km，请安排好到店时间
                </p>
            </div> -->
            <Confirm-Hint></Confirm-Hint>
            <!-- 地址电话方式 -->
            
            <!-- <div class="aui-content">
                <ul class="aui-list aui-media-list choose_list" style="border-bottom: 1px solid rgba(232, 232, 232, 1);">
                    <li class="aui-list-item" style=" text-align: left;">
                        <div style="height:2.1rem;line-height: 2.1rem;">
                            <p style="display:inline-block;width:3.6rem;">用餐门店</p>
                            <p style="display:inline-block;">三祺广场体验店</p>
                        </div>
                        <div style="padding-left:3.6rem;border-bottom: 1px solid rgba(232, 232, 232, 1);height:2.1rem;line-height:2.1rem;">
                            <input type="text" placeholder="具体地址详细地址信息">
                        </div>
                        
                        <div style="border-bottom: 1px solid rgba(232, 232, 232, 1);height:2.1rem;line-height: 2.1rem;">
                            <p  style="display:inline-block;width:3.6rem;">预约电话</p>
                            <span style="display:inline-block;">18842352123</span>
                        </div>
                        
                        <div style="height:2.1rem;line-height: 2.1rem;">
                            <p style="display:inline-block;width:3.6rem;">用餐方式</p>
                            <div style="display:inline-block;">
                                <div style="display:inline-block;">到店食堂</div>
                                <div style="display:inline-block;">到店打包</div>
                            </div>
                        </div>
                    </li>
                </ul>
			</div> -->
            <ConfirmOrderFoodInfo :userPhone = "userInfo"></ConfirmOrderFoodInfo>
            <!-- 商品列表组件 -->
            <div style="width:100%;">
                <ConfirmOrderFoodList ></ConfirmOrderFoodList>
                <!-- -->
                <ConfimOrderFoodSendGift  ></ConfimOrderFoodSendGift>
            </div>
			<!--商品列表-->
			<!-- <div class="aui-content choose_list">
				<ul class="aui-list aui-media-list">
                    <div style="height:2.5rem;border:1px solid #dedede;">
                        <p>下单后立即制作，最快5分钟可出餐</p>
                    </div>
					<li class="aui-list-item iscroll_list">
                        
						<div id="co_orderGoods" class="aui-media-list-item-inner scroller_list" v-if="goodsList">
							<div class="aui-list-item-media" v-for="(item,index) in goodsList" :key="index">
								<img v-lazy="goodsImg(item)" style="height: 100%;width: 100%;"/>
								<em style="background:#EF5423;opacity: 0.6;">x{{item.goodsType == 7?'1':item.goodsNum}}</em>
							</div>
						</div>
					</li>
				</ul>
				<div class="aui-list-item-arrow statistics">
					<p>共<span id="co_totalPiece" style="padding-top: 0.5rem;">{{num}}</span>件</p>
				</div>
			</div>
			<div style="margin-bottom: 0.75rem;margin-top: -0.75rem;">
				<div class="aui-list-item-arrow01 server_show" v-if="sendNameArr && sendNameArr.length != 0" style="background-color: #fff2f2;padding: 0.2rem 0.5rem;">
					<div style="margin-left: 15;text-align: left;" class="aui-list-item-arrow_2">
						<h4>[赠品]</h4>
						<dl>
							<dd v-for="(item,index) in sendNameArr" :key="index">
								<font>{{item}}</font>
							</dd>
						</dl>
					</div>
				</div>
			</div> -->
			<!--商品列表 end-->
			<!--信息列表-->
			<div class="aui-content aui-margin-b-15" style="margin-top:1.5rem;">
				<ul class="aui-list aui-list-in">
					<!-- <li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">商品金额</div>
							<div id="co_totalMoney" class="aui-list-item-right" v-if="goodsTotalMoney">¥{{goodsTotalMoney?Number(goodsTotalMoney).toFixed(2):'0'}} <span v-if="addMoney">(含加工费：¥{{ }})</span></div>
						</div>
					</li> -->
                    <!-- 活动优惠 -->
                    <li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">活动优惠</div> 
							<div id="co_totalMinis" class="aui-list-item-right">{{afterPromTotalMoney?'-':''}}¥{{afterPromTotalMoney?Number(afterPromTotalMoney).toFixed(2):'0'}}</div>
						</div>
					</li>
					<li class="aui-list-item aui-list-item-arrow">
						<div class="aui-list-item-inner" @click="showCoupon">
							<div class="aui-list-item-title">优惠券</div>																													<!--ticketList-->
							<!-- <div class="aui-list-item-right"><span style="color: #EF5423;padding-right: 0.1rem;" v-if="getTicketList.length === 0 && couponCount">{{couponCount}}</span>{{couponFlag}}</div> -->
                            <div class="aui-list-item-right"><span>{{discountMoneyByCoupon?'-':''}}¥{{discountMoneyByCoupon?Number(discountMoneyByCoupon).toFixed(2):'0'}}</span></div>
						</div>
					</li>
                    <!-- 总优惠 -->
					<!-- <li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">优惠金额</div>
							<div id="co_totalMinis" class="aui-list-item-right">¥{{discountMoney}}</div>
						</div>
					</li> -->
					<!--<li class="aui-list-item">
						<div class="aui-list-item-inner">
							<div class="aui-list-item-title">赠品加价</div>
							<div id="co_totalMinis" class="aui-list-item-right">￥{{discountMoney}}</div>
						</div>
					</li>-->
				</ul>
			</div>
			<!--信息列表 end-->
			<div class="aui-content aui-margin-b-15" v-if="false">
				<ul class="aui-list aui-form-list liuyan">
					<li class="aui-list-item">
						<div class="aui-list-item-inner" style="align-items:flex-start;">
							<div class="aui-list-item-label" style="line-height:2rem;">买家留言：</div>
							<div class="aui-list-item-input">
								<textarea placeholder="选填：输入留言信息" v-model="mynode" ref="note" maxlength="100"></textarea>
							</div>
						</div>
					</li>
				</ul>
			</div>
			<div class="total_sf">
				<h2><span id="co_realpay" >实付金额：¥ {{totalMoney?Number(totalMoney).toFixed(2):'0'}}</span> <p style="display: inline;" v-if="false">(省：¥ 1.00)</p> </h2>
				<p>如需发票，请到门店索取</p>
			</div>
			<!--立即下单-->
			<div style="height:4rem;" id="scrollTopBox"></div>
			<!--去结算 end-->
		</div>
		<confirm-gift-card ref="giftCard"></confirm-gift-card>
		<confirm-coupon ref="coupon" :couponArr="couponArr" :couponArrHtm="couponArrHtm" :couponMoney="couponM" :money="Number(totalMoney)" :getCouponMoney="changeCoupon"></confirm-coupon>
		
		<div class="zxSettle_acount aui-btn aui-btn-danger aui-btn-block aui-btn-sm" style="height: 2.5rem;line-height: 2.5rem;border-radius: 0px;font-size: 1rem;padding: 0px;">
			<div @click.stop="confirmOrderFoods">提交订单</div>
		</div>	
		<!--<confirm-order-pursekey ref="pursekey" :sendOrder="toPay"></confirm-order-pursekey>-->

	</div>
</template>

<script>
	import axios from 'axios';
	import { MessageBox } from '../../ui-components'
	import { Toast } from '../../utils/toast';
	import { mapGetters, mapActions, mapMutations } from "vuex";
	import MyHeader from "../header";
	import ConfirmCoupon from "../../real-components/ConfirmOrder/ConfirmCoupon";
	import ConfirmOrderPursekey from "../../real-components/ConfirmOrder/ConfirmOrderPursekey";
	import ConfirmGiftCard from "../../real-components/ConfirmOrder/ConfirmGiftCard";
	import {saomagou} from "../../config/orderTypeCode";
    import {showLoading, hideLoading} from "../../utils/loading";
    import ConfirmOrderFoodList from "../../real-components/ConfirmOrderFood/ConfirmOrderGoodFoodList";
    import ConfimOrderFoodSendGift from "../../real-components/ConfirmOrderFood/ConfimOrderFoodSendGift";
    import ConfirmHint from "../../real-components/ConfirmOrderFood/ConfirmOrderHint";
    import ConfirmOrderFoodInfo from "../../real-components/ConfirmOrderFood/ConfirmOrderFoodInfo";
	export default {
		props: {},
		components: {
			"my-header": MyHeader,
			"ConfirmCoupon": ConfirmCoupon,
			"confirm-order-pursekey": ConfirmOrderPursekey,
            "ConfirmGiftCard": ConfirmGiftCard,
            "ConfirmOrderFoodList": ConfirmOrderFoodList,
            "ConfimOrderFoodSendGift": ConfimOrderFoodSendGift,
            "Confirm-Hint": ConfirmHint,
            "ConfirmOrderFoodInfo": ConfirmOrderFoodInfo,
            
		},
		computed: {
			...mapGetters('wxh', [
				'sessionId',
				'userInfo'
			]),
			...mapGetters('zx', [
				"getTicketList", "getAvailAmount", "getUseGiftCard","getOrderFlag"
			]),
			...mapGetters('cjy', [
				"selectGiftList", "selectLadderList", "buyMoreData"
			]),
			...mapGetters('qxz', [
				"getStoreList"
			]),
			ticketList() {
//				if(this.getTicketList.length === 0) {
//					if(this.couponCount){
//						this.couponFlag = "组可用";
//					}else{
//						this.couponFlag = '';
//					}
//				} else {
//					this.couponFlag = "已选择";
//				}
//				return this.couponFlag;
			},
			couponM() {

			},
			totalMoney() {
				return this.goodsPromTotalMoney;
			},
		},
		watch: {
			totalMoney(newVal,oldVal){
				console.log(newVal,oldVal,this.getTicketList.length,'应付金额*--**--*-*-*-*-*-*-*-*-*-应付金额')
//				为确保数据同时渲染在请求完获取金额的接口后再显示优惠券信息
				if(this.getTicketList.length === 0) {
					if(this.couponCount){
						this.couponFlag = "组可用";
					}else{
						this.couponFlag = '';
					}
				} else {
					this.couponFlag = "已选择";
				}
				console.log(this.couponFlag,'应付金额*--**--*-*-*-*-*-*-*-*-*-应付金额2')
//				return this.couponFlag;
				
			}
		},
		data() {
			return {
				mynode: '',
				addMoney: '',
				goodsList: [],
				num: 0,
				orderData: null,
				goodsTotalMoney: 0, // 商品金额
                discountMoney: 0, // 总优惠的金额
                discountMoneyByCoupon:0, //优惠券优惠
                afterPromTotalMoney:0, //其他优惠
				goodsPromTotalMoney: 0, //实付金额
				couponArr: null, // 优惠券数组
				couponArrHtm: null, // 用于展示的优惠券数组
				couponFlag: '', //是否选择优惠券
				couponMoney: 0, // 优惠券优惠金额
				money: 0, //总金额
				storeOrderNo: null, // 线下订单号
				shopId: 0, // 线下门店
				moneyWithoutC: 0, //钱包免密金额
				keyall: null, // 钱包密码
				showMask: false, //是否需要用戶輸入密碼
				walletStatus: null, // 是否已经设置钱包密码
				sendNameArr: [], // 赠品名称数组  赠优惠券 赠商品
				shopCartIds:[],      //用于下单的参数  商品的rid
				couponCount:0, //可用优惠券
				clickFlag:true,  // 防止两次快速点击 调用两次下单接口
				storeName:null, // 扫码购门店名称
				ladderList:[],
                giftList:[],
                getToken:"",//保存获取的getToken值
			}
		},
		methods: {
			...mapMutations('zx', [
				"setUseGiftCard","setOrderFlag",
			]),
			...mapMutations('cjy', [
				'SET_OFF_LINE_SELECT_DATA'
			]),
			...mapActions('cjy',[
				"clearOffLineDetail"
            ]),
            //确定选择优惠券时，调取后台接口实时获取金额信息
			getMoneyAgain(flag) {
				//展示loading效果
			    // showLoading();
				var arr = [];
				// this.setGiftSendArr(arr); // 清空礼品包
				
				let url = window.api.trade_host + "/marketCenter/calOrder";
				let params = {
					storeCode: window.localStorage.getItem('storeCode'),
				};
				params.qrCodeList = this.getCouponParams(); //优惠券集合 
				// if(this.giftList && this.giftList.length != 0) {
				// 	params.giftVOList = this.giftList; // 赠品id 商品id 活动id  赠品次数 以逗号分隔
				// }
				// if(this.ladderList && this.ladderList.length != 0) {
				// 	params.ladderIdList = this.ladderList; //商品id 阶梯满id 活动id  以逗号分隔
                // }
                // 是否是第一次调用该接口 true代表第一次调用  false代表第二次开始调用
                params.callFirstTime = flag;
				let config = {
					url: url,
					method: "POST",
					data: params,
					headers: {
						'sessionId': window.localStorage.getItem("sessionId")
					}
				};
				
				try{
	        		axios(config).then((res) => {
						if(res.data.returnCode == 0){
							hideLoading();
							MessageBox.confirm('商品失效请重新下单').then((action)=>{
								this.$router.push('cart');
							})
                    		return
						}
                        if(!flag){
                            // hideLoading();
                        }
                        if(res.data.returnCode == 1) {
                            //将后台接口返回信息存到vuex 页面跳转时再获取，不再走后台
                            this.setConfrimOrderRes(res);

                        }
                        this.confrimOrderInitData(res);
					})	
        		}catch(err) {
        			//隐藏loading效果
					hideLoading();
					MessageBox.confirm('商品失效请重新下单').then((action)=>{
                        this.$router.push('cart');
                    })
                    return
        		}
				
            },
            confrimOrderInitData(res){
                if(res.data.returnCode == 1) {
                    this.discountMoneyByCoupon = res.data.data[0].discountMoneyByCoupon; //优惠券优惠金额
                    this.afterPromTotalMoney = res.data.data[0].afterPromTotalMoney;//优惠活动优惠金额
                    // console.log(this.discountMoneyByCoupon,this.afterPromTotalMoney,'）））））））怎么没有货渠道优惠金额信息））））')
                    this.money = Number(res.data.data[0].resultOrderTotalMoney); //应付金额
                    this.couponMoney = Number(res.data.data[0].orderDiscountMoney); // 总优惠金额
                    this.goodsMoney = Number(res.data.data[0].promTotalMoney); //商品金额
                    this.addMoney = Number(res.data.data[0].totalWorkingFee); // 加工费用
                    this.normalMoney = Number(res.data.data[0].totalCgoodsFee); //常规商品费用 优惠后
                    this.bigMoney = Number(res.data.data[0].totalBgoodsFee); //大件商品费用 优惠后
                    this.goodsAddMoney = Number(res.data.data[0].addMoney); //加价购
                    //暂时未用到的数据
                    let coupon = res.data.data[0].couponCodeUsedList; //最优优惠券组
                    
                    //暂时未用到的数据
                    this.setToken(res.data.data[0].token);//服务器token用于后台判断是否是第一次尝试下单
                    var giftArr = res.data.data[0].giftCoupounsList //下面不展示赠品信息了只展示赠送的优惠券
                    this.setGiftSendArr(giftArr);
                    //购物车商品数据 因为需求改动购物车数据不从购物车页面传递所以用发送事件的方式将商品数据发送给父组件
                    let commonGoodsList = res.data.data[0].commonGoodsList; //常规商品数组
                    let bigGoodsList = res.data.data[0].bigGoodsList; //大件商品数组
                    let goodsList = this.addDistrbution(commonGoodsList).concat(this.addDistrbution(bigGoodsList)); //增加了distributiontype属性的总商品数组
                    this.$emit('sendGoodsList',goodsList);

                    //获取可用优惠券信息
                    if(res.data.data[0] && res.data.data[0].coupounsList && res.data.data[0].coupounsList.length){
                        let coupounsList = res.data.data[0].coupounsList;	
                        this.couponCount = res.data.data[0].coupounsList.length;
                        this.couponArr = this.newCoupons(coupounsList, 1);
                        this.couponArrHtm = this.newCoupons(coupounsList, 2);
                        // console.log(coupounsList,this.couponArr,this.couponArrHtm,'…………………………优惠券数组打印*****8')
                    }
                    // this.checkeMoneySend(); //每次获取到金额信息就判断是否需要加运费
                } else {
                    Toast({
                        message: '计算金额失败',
                        type: "fail",
                        duration: 1000
                    });
                }
            },
			//获取门店
			getStoreName(){
				var code = localStorage.getItem('storeCode');
				var arr = this.getStoreList;
				for(let i = 0; i < arr.length; i++){
					if(arr[i].storeCode == code){
						this.storeName = arr[i].storeName;
					}
				}
//				console.log(code,'门店',this.getStoreList);
			},
			//获取商品信息
			getGoodsList() {
                this.goodsList = this.$store.state.cjy.offLineSelectData;
                console.log(JSON.stringify(this.goodsList),'购物车数据')
				this.getGoodsNum();
			},
			initData() {
				//				this.goodsList = this.$store.state.cjy.checkedCartList;
				//				var res = this.$route.query.res;
				//				var obj = res.data.data[0];
				//				console.log(res, '路由参数');
				//				if(res != null) {
				//					console.log(res.data.data[0].couponsInfo, '优惠券数组');
				//				}
				//				if(res != null) {
				//					this.goodsList = obj.goodsList;
				//					this.storeOrderNo = obj.storeOrderNo;
				//					this.shopId = obj.shopId;
				//					this.getGoodsNum();
				//					this.goodsTotalMoney = obj.goodsTotalMoney; // 优惠活动后的金额
				//					//this.goodsMoney = obj.goodsTotalMoney; // 用于计算优惠券金额
				//					this.goodsPromTotalMoney = obj.goodsPromTotalMoney; // 实付金额
				//					this.discountMoney = obj.discountMoney;
				//					this.couponArr = this.newCouponArr(obj.couponsInfo, 1);
				//					this.couponArrHtm = this.newCouponArr(obj.couponsInfo, 2);
				//
				//					var giftArr = res.data.data[0].giftVOPresentList.concat(res.data.data[0].couponCodePresentList);
				//					this.getSendNameArr(giftArr);
				//					console.log(giftArr,'赠品信息')
				//					console.log('首次渲染路由 实付金额', obj.goodsPromTotalMoney);
				//					console.log('首次渲染页面展示 实付金额', this.goodsPromTotalMoney);
				//					console.log(obj.goodsTotalMoney, 'res.data goodsTotalMoney获取路由参数2');
				//					console.log(this.couponArr, 'res.data.data couponsInfo获取路由参数3');
				//					console.log(obj.discountMoney, 'res.data.data couponsInfo 获取路由参数4');
				//				}
			},
			goodsImg(goodsItemData) {
	            if (goodsItemData && goodsItemData.urllist) {
	                if(goodsItemData.urllist.length) {
	                	for(let i = 0 ; i < goodsItemData.urllist.length; i++){
	                		if(goodsItemData.urllist[i].imgurltype == 1){
	                			return goodsItemData.urllist[i].imgurl || "static/image/demo2.png";
	                		}
	                	}
	                } else {
	                    return "static/image/demo2.png";
	                }
	            } else {
	                return "static/image/demo2.png";
	            }
	        },
			getSendNameArr(giftArr) {
				console.log(giftArr,'赠品包1');
				this.sendNameArr = [];
				var arr = giftArr;
				if(arr && arr.length) {
					for(let i = 0; i < arr.length; i++) {
						//				 		console.log(arr[i],'礼包');
						if(arr[i] != null && arr[i].giftName) {
							this.sendNameArr.push(arr[i].giftName);
						}
						if(arr[i] != null && arr[i].couponName) {
							this.sendNameArr.push(arr[i].couponName);
						}
					}
				}
				console.log('赠品包',this.sendNameArr)
			},
			//过滤优惠券数组增加同组标志
			newCouponArr(arr, num) {
				var newArr = [];
				for(let i = 0; i < arr.length; i++) {
					for(let j = 0; j < arr[i].couponCodeList.length; j++) {
						arr[i].couponCodeList[j].relIndex = i;
						newArr.push(arr[i].couponCodeList[j]);
					}
				}
				if(num === 1) {
					return newArr;
				} else if(num === 2) {
					return arr;
				}

			},
			//获取优惠券信息
			getCoupon() {
				let url = window.api.trade_host + "/marketCenter/getCalScanCodeCart/" + window.localStorage.getItem('storeCode') + "/false"
				let config = {
					url: url,
					method: "GET",
					headers: {
						'sessionId': window.localStorage.getItem("sessionId")
					}
				};
				axios(config).then((res) => {
					if(res.data.data[0] && res.data.returnCode == 1) {
						if(res.data.data[0].couponListCanBeUsed){
							var arr = res.data.data[0].couponListCanBeUsed;
							this.couponCount = res.data.data[0].couponListCanBeUsed.length;
							console.log(res.data.data[0].couponListCanBeUsed.length);
							console.log(arr, '线下扫码原生数组')
							this.couponArr = this.newCouponArr(arr, 1);
							this.couponArrHtm = this.newCouponArr(arr, 2);
						}
					}
					//如果没有可使用的优惠券 或者 没有获取到优惠券信息 则直接调用获取金额信息接口    如果有可使用的优惠券 则在优惠券组件中获取最优优惠券再请求获取金额信息接口
					if(!res.data.data[0] || !res.data.data[0].couponListCanBeUsed || res.data.data[0].couponListCanBeUsed.length == 0){
						this.changeCoupon();
					}
				})
			},
			changeCoupon() {
				let url = window.api.trade_host + "/marketCenter/calScanCodeOrder";
				let params = {
					storeCode: window.api.storeCode //门店编码
				};
				console.log(this.couponFlag,'this.couponFlag获取优惠券’')
				
				let arr = this.getCouponParams();
				params.qrCodeList = arr;
				if(this.giftList && this.giftList.length != 0) {
					params.giftVOList = this.giftList; // 赠品id 商品id 活动id  赠品次数 以逗号分隔
				}
				if(this.ladderList && this.ladderList.length != 0) {
					//					console.log(123458888)
					params.ladderIdList = this.ladderList; //商品id 阶梯满id 活动id  以逗号分隔
				}
				let config = {
					url: url,
					method: 'POST',
					data: params,
					headers: {
						'sessionId': this.sessionId,
					},
				};

				try{
					axios(config).then((res) => {
						console.log(res.data, '选择优惠券及时计算金额1');
						console.log(res.data.data, '选择优惠券及时计算金额2');
						console.log(res.data.data[0], '选择优惠券及时计算金额');
						console.log(res.data.data[0].goodsTotalMoney, '商品总金额');
//						console.log(res.data.data[0].goodsPromTotalMoney, '优惠后总金额');
//						console.log(res.data.data[0].discountMoney, '优惠金额');
						
						this.sendNameArr = []; // 清空礼品包
						
						if(res.data && res.data.data && res.data.data.length){
							this.goodsTotalMoney = Number(res.data.data[0].promTotalMoney); //商品金额
                            this.discountMoney = Number(res.data.data[0].orderDiscountMoney); // 总优惠金额
                            this.discountMoneyByCoupon = Number(res.data.data[0].discountMoneyByCoupon); //优惠券优惠
                            this.afterPromTotalMoney = Number(res.data.data[0].afterPromTotalMoney); //活动优惠
                            // this.addMoney = Number(res.data.data[0].totalWorkingFee); // 加工费用  暂时没有加工
							this.goodsPromTotalMoney = Number(res.data.data[0].resultOrderTotalMoney); //总金额  包含加工费 加价购等 实付金额
							var giftArr = res.data.data[0].giftVOPresentList.concat(res.data.data[0].couponCodePresentList);
							this.getSendNameArr(giftArr);
						}
						this.setOrderFlag(true); // 获取到金额信息  允许用户点击提交订单按钮
						hideLoading();  //隐藏loading
					})
				}catch(err){
					hideLoading();
				}
			},
			goInfomation() {
				this.$router.push({
					path: 'orderInformation',
					query: {
						arr: this.goodsList
					}
				});
			},
			//	       	 展示优惠券
			showCoupon() {
				//console.log("sss")
				this.$refs.coupon.showCover()
			},
			//获取总金额
			getGoodsNum() {
				if(this.goodsList.length != 0) {
					for(let i = 0; i < this.goodsList.length; i++) {
						if(this.goodsList[i].goodsType == 7) {
							this.num += 1
						} else {
							this.num += this.goodsList[i].goodsNum;
						}
					}
				}
			},
			goBack() {
				window.history.back();
			},
			checkeParams() {

			},
			getCouponParams() {
				let arr = this.getTicketList;
				let newArr = [];
				for(let i = 0; i < arr.length; i++) {
					newArr.push(arr[i].qrCode);
				}
				return newArr;
			},
			//获取购物车商品活动信息
			getSelectGiftList() {

				var arr = this.selectGiftList; // 满增阶梯
				
				if(arr && arr.length != 0) {
					for(var i = 0; i < arr.length; i++) {
						
						//如果存在goodsCode就传goodsCode 如果不存在goodsCode但是存在goodsCodeList就便利之后传过去
						if(arr[i].goodsCode){
							var newArr = [];
							newArr.push(arr[i].goodsCode);   //商品code
							newArr.push(arr[i].promLadderId);    // 阶梯满id
							newArr.push(arr[i].promCode);  //活动code
							this.ladderList.push(JSON.stringify(newArr));
							
						}else if(arr[i].goodsCodeList && arr[i].goodsCodeList.length){
							
							for(let j = 0; j < arr[i].goodsCodeList.length; j++) {
								var newArr = [];
								newArr.push(arr[i].goodsCodeList[j]);  //商品列表
								newArr.push(arr[i].promLadderId);  // 订单返利 阶梯满id 
								newArr.push(arr[i].promCode);      // 活动code
								this.ladderList.push(JSON.stringify(newArr));
							}
							
						}
					}
				}
			},
			getSelectLadderList() {
				var arr = this.selectLadderList; // 返利阶梯   只有订单返利阶梯才有可能送单张优惠券

				if(arr && arr.length != 0) {
					for(var i = 0; i < arr.length; i++) {
						
						//newArr.push(arr[i].goodsList);
						for(let j = 0; j < arr[i].goodsList.length; j++) {
							var newArr = [];
							newArr.push(arr[i].goodsList[j]);  //商品列表
							newArr.push(arr[i].promLadderId);  // 订单返利 阶梯满id 
							newArr.push(arr[i].promCode);      // 活动code
							this.ladderList.push(JSON.stringify(newArr));
						}
					}

				}
			},
			getBuyMoreData() {
				var arr = this.buyMoreData;

				
				var giftVoList = arr.filter ( (item) => {
					return item.giftVO && item.giftVO.giftGoodsList && item.giftVO.giftGoodsList.length > 0
				})
				console.log(giftVoList,'giftVoList5555555555')
				if(giftVoList.length != 0) {
					for(var i = 0; i < giftVoList.length; i++) {
						
						for(let j = 0; j < giftVoList[i].goodsList.length; j++) {
							var newArr = [];
							newArr.push(giftVoList[i].goodsList[j]);
							newArr.push(giftVoList[i].promCode);
							newArr.push(giftVoList[i].selectNum);
							if(giftVoList[i].selectNum != 0) {
								this.giftList.push(JSON.stringify(newArr));
							}

						}
					}
				}
			},
			//获取购物车商品活动信息结束
			getLadderParams(){
				return this.ladderList || [];
			},
			getGiftParams(){
				return this.giftList || [];
			},
			// 获取商品rid
			getShopCartIds(){
				//区分大件商品和常规商品  0 常规   1 大件
				for(var i = 0; i < this.goodsList.length; i++){
					var obj = {}
					obj['rid'] = this.goodsList[i].rid;
					this.shopCartIds.push(obj);
				}
				return this.shopCartIds;
			},
			  //如果是安卓机,调整页面margin-bottom供用户看到input框
	        initInputStyle() {
	            let isAndroid = navigator.userAgent.indexOf("Android") > -1;
	            if (isAndroid) {
	            	console.log("/-*****-/---1---");
					let box = document.getElementById('scanNodeBug');
					let box2 = document.getElementById('scrollTopBox');
					box2.style.height = '18rem';
	                let scrollTopContainer = document.body;
//	                console.log(box.scrollTop,'11111111111')
					box.scrollTop = 450;
//					console.log(box.scrollTop,'11111111111')
	                //给一个scrollTop值的变化，自动滑上去
	                let distance = parseInt(getComputedStyle(box, null).marginBottom.slice(0, -2));
	                let duration = 200 / 16.7;
	                let speed = distance / duration;
	                this.scrollAnim = setInterval(() => {
	                    scrollTopContainer.scrollTop += speed;
	                    if (scrollTopContainer.scrollTop >= distance) {
	                    	console.log("/-*****-/---3---");
	                        scrollTopContainer.scrollTop = distance;
	                        clearInterval(this.scrollAnim);
	                    }
	                }, 16.7);
	            }
	        },
	        unsetStyle() {
//	        	console.log(999)
	            //清除计时器
	            clearInterval(this.scrollAnim);
	            this.scrollAnim = null;
	            let box = document.getElementById('scanNodeBug');
				let box2 = document.getElementById('scrollTopBox');
				box2.style.height = '4rem';
				box.scrollTop = 220;
				 console.log(box.scrollTop,'22222222222')
	        },
	        //监听买家留言框的focus事件 开始
	        initTextareaFocusEvent() {
	        	console.log(this.$refs.note)
	            this.$refs.note.onfocus = () => {
	                console.log("input框框获取到了焦点");
	                this.initInputStyle();
	            }
	            this.$refs.note.onblur = () => {
	                console.log("失去焦点");
	                //重置样式
	                this.unsetStyle();
	                
	            }
	        },
	       //从支付页点返回处理
			checkPayBack(){
				let flag = this.$store.getters.getNativeBackFlagForPay;
				let flag2 = !this.$store.state.cjy.offLineSelectData || this.$store.state.cjy.offLineSelectData == 0;
				if(flag && flag2){
					this.$store.commit("setNativeBackFlagForPay", false);
					this.$router.push({path:'order',query:{orderStatus:1}});
					return true;
				}else if(!flag && flag2){
					this.$router.push({path:'home'});
					return true;
				}
				return false;
            },
            getTokens(){//获取getToken值
                console.log("*******************------------------")
				let url =  window.api.trade_host + "/order/getToken";
				let config = {
					url: url,
					method: "GET",
					headers: {
						'sessionId': window.localStorage.getItem("sessionId")
					}
				};
				axios(config).then((res)=>{
					this.getToken = res.data.data[0];
				})
				
            },
            //堂食订单提交方法
            async confirmOrderFoods(){
                console.log("堂食的提交订单")
                // let params = {};
                let params = {
                    // addressId:this.address.addressid,1
                    // cartId:this.checkedCartList[0].cartId,
                    deliveryType:this.getConfirstyle && this.getConfirstyle == "到店食堂" ?"DDST":"DDDB",  //配送方式
                    // note:this.getMynode,1
                    // shopCartIds:this.shopCartIds,
                    storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                    // orderDeliveryTms,1
                    // latticeName:latticeName,// wms网格 1
                    orderType:'3',
                    orderMobile:this.getConfirmobile,
                };
                let electronicInvoice = {//发票的传参
                    invoicesTitleId:this.$store.state.hzh.getBillInfor,
                    invoiceContext:this.$store.state.hzh.BillContent
                }
                // if(this.PutAShopLacks){
                //     params = {
                //         addressId:this.address.addressid,
                //         // cartId:this.checkedCartList[0].cartId,
                //         deliveryType:this.getDeliveryType,  //配送方式
                //         note:this.getMynode,
                //         // shopCartIds:this.shopCartIds,
                //         storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                //         orderDeliveryTms,
                //         latticeName:latticeName,// wms网格 
                //         outStockModel:this.PutAShopLacks
                //     };
                // }
                // if(this.$store.state.hzh.getBillInfor.length != 0){
                //     params = {
                //         addressId:this.address.addressid,
                //         // cartId:this.checkedCartList[0].cartId,
                //         deliveryType:this.getDeliveryType,  //配送方式
                //         note:this.getMynode,
                //         // shopCartIds:this.shopCartIds,
                //         storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                //         orderDeliveryTms,
                //         latticeName:latticeName,// wms网格 
                //         electronicInvoice
                //     };
                // }else{
                //     params = {
                //         addressId:this.address.addressid,
                //         // cartId:this.checkedCartList[0].cartId,
                //         deliveryType:this.getDeliveryType,  //配送方式
                //         note:this.getMynode,
                //         // shopCartIds:this.shopCartIds,
                //         storeCode:localStorage.getItem('storeId'), //调试用的 '5555555'  localStorage.getItem('storeId')   3df87595-762d-414e-be0f-6b6d8361f5d2  73ece0ae-ba0e-4501-b993-d727b9ae25c2
                //         orderDeliveryTms,
                //         latticeName:latticeName,// wms网格 
                        
                //     };
                // }
                console.log("提交订单------------------>",params)
                // let flag = this.checkBuyByCard();//入参 walletPayed 0 代表常规支付   1代表钱包支付
                // if(flag){
                //     params.walletPayed = 1;
                // }else{
                //     params.walletPayed = 0;
                // }
                // var couponParams = this.getCouponParams();  // 获取优惠券参数
                // if(couponParams && couponParams.length != 0){
                //     params.qrCodeList = couponParams;
                // }

                // var ladderIdList = this.getLadderParams(); // 获取阶梯返利满赠参数
                // if(ladderIdList && ladderIdList.length != 0){
                //     params.ladderIdList = ladderIdList;
                // }

                // var giftVOList = this.getGiftParams();
                // if(giftVOList && giftVOList.length != 0){
                //     params.giftVOList = giftVOList;
                // }

                let query = this.$route.query.name;

                // params.deliveryAddress = this.getAddressDetail;

                params.token  = this.getToken;  // 传token用于后台识别
                // console.log(this.getToken,'this.getToken获取token提交');
                // console.log(params,'下单参数');
                let config = {
                    url: window.api.trade_host+'/order/insertDto',
                    method: 'POST',
                    data: params,
                    headers: {'sessionId': this.sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
                }
                // if(this.address && orderDeliveryTms.length > 0){
                    try{
                        let data = await axios(config);
                        console.log(params,'下单请求参数信息')
                        this.clickFlag = true;  //接口返回  解除点击禁用
                        console.log(data,'返回参数')
                        if(data.data.returnCode == 1 ){

                            console.log(this.totalMoney,'订单生成');

                            var arr = [];
                            this.changeCheckedCartList(arr);
                            this.$store.dispatch('cjy/queryCart');

                            var orderNo = data.data.data[0];
                            if(this.totalMoney != 0){
                                this.$router.push({name: "pay", params: {orderNo:orderNo,orderType:normal}});
                            }else{
                                this.$router.push({name: "paysuccessfully", params: {orderNo:orderNo,orderType:normal}});
                            }
                        }else{
                            var token = data.data.data[0];
                            // console.log('token失败------',this.getToken,'this.getToken获取token失败------');
                            this.setToken(token);  //下单失败 后台重新返回 token 用于再次下单
                            MessageBox.confirm('商品失效请重新下单').then((action)=>{
                                this.$router.push('cart');
                            })
                        }
                    }catch(err) {
                        console.log(err,'错误信息')
                        this.clickFlag = true;  //接口返回  解除点击禁用
                        Toast({
                            message: '生成订单失败',
                            duration: 1000,
                            type: 'fail'
                        });
                    }
                // }
            },
			async toPay() {
				
				// 判断获取金额信息接口是否已返回数据  没返回就禁止下单
        		if(!this.getOrderFlag){
        			return;
        		}
				
				//防止多次点击下单
        		if(!this.clickFlag){
        			return ;
        		}
				
				this.clickFlag = false;  // 点击后置为禁用状态
				var that = this;
				var myTimer = setTimeout(function(){
        			that.clickFlag = true;
        		},5000)
				
				let params = {
					cartId: this.goodsList[0].cartId,
					note: this.mynode,
					storeCode: window.api.storeCode,
					shopCartIds: this.getShopCartIds()
				};
				console.log(this.couponFlag,'this.couponFlag')
				if(this.couponFlag != '') {
					let arr = this.getCouponParams();
					params.qrCodeList = arr;
				}
				var ladderIdList = this.getLadderParams(); // 获取阶梯返利满赠参数
        		if(ladderIdList && ladderIdList.length != 0){
        			params.ladderIdList = ladderIdList;
        		}
        		
        		var giftVOList = this.getGiftParams();
        		if(giftVOList && giftVOList.length != 0){
        			params.giftVOList = giftVOList;
        		}
        		
				params.walletPayed = 0;
				console.log(params, '请求参数');

				let config = {
	            	url: window.api.trade_host+'/order/insertScanOrderDto',
	            	method: 'POST',
	            	data: params,
	            	headers: {'sessionId': this.sessionId, 'Content-Type':'application/json', 'Accept' : 'application/json'},
	            }
				

				try {
                    var res =  await axios(config);
                    console.log(res);
                    console.log(res.readyState, res.status);
                    console.log(res);
                    console.log(res.data);
                    
                    this.clickFlag = true;  //接口返回  解除点击禁用
                    
                    if(res.status == 200) {
                        console.log(res);
                        if(res.data.returnCode == 1) {
                            console.log('订单生成');
                            
                            var arr = [];
                            this.SET_OFF_LINE_SELECT_DATA(arr);  //清除购物车数据
                            
                            var orderNo = res.data.data[0];
                            
                            if(this.totalMoney != 0){
                                this.$router.push({name: "pay", params: {orderNo:orderNo,orderType:saomagou}});
                            }else{
                                this.$router.push({name: "paysuccessfully", params: {orderType:saomagou}});
                            }

                        } else {
                            console.log('下单失败')
                            Toast({
                                message: res.data.msg,
                                duration: 1000,
                                type: 'fail'
                            });
                        }
                    } else {
                        Toast({
                            message: '生成订单失败',
                            duration: 1000,
                            type: 'fail'
                        });
                    }
				} catch(err) {
					this.clickFlag = true;  //接口返回  解除点击禁用
					Toast({
						message: '生成订单失败',
						duration: 1000,
						type: 'fail'
					});
				}
			}
		},
		beforeDestroy() {
			
			hideLoading();
			
			this.setUseGiftCard(false);
			this.setOrderFlag(false); // 将提交按钮设置为禁用状态
			//清楚购物车数据
			this.clearOffLineDetail();
			//	    	this.setFpObj({});   // 重置发票对象的在indexvue中实现
		},
		created() {
			
			console.log(12345678999996666999999999999999)
			// if (this.checkPayBack()) return;  //判断从支付页点原生返回 处理
			
			this.getTokens();//获取token值提交订单传后台
			this.initData();
			this.getGoodsList();
			this.getCoupon();
//				this.changeCoupon();  //初始化金额信息
			this.getStoreName();  // 获取扫码购门店名称
			this.getSelectGiftList(); //获取满增阶梯信息 ladderList
			this.getSelectLadderList(); // 获取返利阶梯信息  ladderList
            this.getBuyMoreData(); // 获取 买增 信息  giftList
            

			this.getMoneyAgain(true);//获取购物车下单的所有商品信息1111
			
		},
		mounted() {
				//展示loading
			showLoading();
			setTimeout(() => {
				hideLoading();
			},3000)
//	        this.initTextareaFocusEvent();
	    },
	}
</script>

<style scoped="scoped">
	.settle_accounts {
		height: 3rem;
		background: rgba(255, 255, 255, 0.9);
		overflow: hidden;
		position: fixed;
		width: 100%;
		left: 0;
		bottom: -1px;
		display: table;
		border-top: 1px solid #eaeaea;
		z-index: 1;
	}
	
	.scroller_list {
		overflow-y: auto;
	}
	
	.iscroll_list {
		height: 5.5rem !important;
	}
	
	.scroller_list {
		position: relative;
	}
	
	.vue_app {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}
	
	.content {
		flex: 1;
		overflow-y: auto;
		width: 100%;
	}
	.zxSettle_acount {
		height: 3rem;
		background: rgba(255, 255, 255, 0.9);
		width: 100%;
		border-top: 1px solid #eaeaea;
		padding: 0.5rem 0.75rem 0;
	}
	.choose_list .statistics {
        padding-top: 1.9rem;
        top:2.5rem;
	}
</style>